package com.fedming.bottomnavigationdemo;

import static com.fedming.bottomnavigationdemo.mq.MqConsumer.basicConsume;
import static com.fedming.bottomnavigationdemo.mq.MqConsumer.handleMessage;
import static com.fedming.bottomnavigationdemo.mq.MqConsumer.setupConnectionFactory;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aill.androidserialport.ByteUtil;
import com.aill.androidserialport.SerialPort;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fedming.bottomnavigationdemo.Adapter.ViewPagerAdapter;
import com.fedming.bottomnavigationdemo.Bean.MedicationBean;
import com.fedming.bottomnavigationdemo.Bean.ShoutInfo;
import com.fedming.bottomnavigationdemo.Call.AudioCallActivity;
import com.fedming.bottomnavigationdemo.Call.VideoCallActivity;
import com.fedming.bottomnavigationdemo.Call.my_SignalClient;
import com.fedming.bottomnavigationdemo.Fragment.HomeFragment;
import com.fedming.bottomnavigationdemo.Fragment.HospitalFragment;
import com.fedming.bottomnavigationdemo.Util.CameraUtils;
import com.fedming.bottomnavigationdemo.Util.CheckSettingUtils;
import com.fedming.bottomnavigationdemo.Util.HttpUtils;
import com.fedming.bottomnavigationdemo.Util.NetWorkUtils;
import com.fedming.bottomnavigationdemo.Util.TimeUtil;
import com.fedming.bottomnavigationdemo.Util.WifiHostBiz;
import com.fedming.bottomnavigationdemo.Util.customViewGroup;
import com.fedming.bottomnavigationdemo.layout.ViewPagerSwipeRefreshLayout;
import com.fedming.bottomnavigationdemo.mq.MqConsumer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.OkHttpClient;
import pub.devrel.easypermissions.EasyPermissions;

public class HomeActivity extends AppCompatActivity {

    public ViewPager viewPager;
    public MenuItem menuItem;
    public BottomNavigationView bottomNavigationView;
    public Button help;
    public Button change_medi;
    public Button calling;
    public Button hidden_setting;
    public String TAG = "HomeActivity";
    public ImageView wifi ;
    ViewPagerSwipeRefreshLayout mSwipeRefreshLayout;
    ViewPagerAdapter mViewPagerAdapter;
    public int mCurrentIndex;
    public OkHttpClient client;

    public static String room = "";
    public static String code = "";
    public static Integer patientId = 0;
    public static String name = "";
    public static String gender = "";
    public static String profile = "";
    public static Integer age = 0;
    public static String admissionDate = "";
    public static Integer level = 0;
    public static String pno = "";
    public static String office = "";
    public static String doctor = "";
    public static String nurse = "";
    public static JSONArray conditions = new JSONArray();
    public static JSONArray advices = new JSONArray();
    public static List<MedicationBean> medicationBeans = new ArrayList<>();

    public static String bedID = "";
    public static String localdeviceID = "";
    public static String stationDeviceID = "";
    public static int stationId = 0;
    public static String socketUrl = "";
    public static String server_ip = "";
    public static String info_port = "";
    public static String call_port = "";
    public static String queue_num = "";
    public static String uuid = "";
    public static String path = "/bed/signal";
    public static String path2 = "/station/broadcast/getAll";
    public static String path3 = "/bed/device/getStationId";
    public static String path4 = "/bed/callRecord";
    public static String path5 = "/call/isOnline";
    public static boolean is_help = false;
    public static boolean is_change = false;
    public static String t1 = "";
    public static String t2 = "";
    public static String t3 = "";

    public static String hospital_url = "http://www.jinshanhealthcity.com/Hospital/2672.html";

    private boolean isPhysicalButton = false;

    public static Timer timer = new Timer();

    //private static String stationId;

    final String ACTION = "timeTask.action";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //getSupportActionBar().hide();//隐藏标题栏
        super.onCreate(savedInstanceState);
//        ActivityCompat.requestPermissions(this, new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, 200);
//
//        Intent intent1 = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + this.getPackageName()));
//        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        this.startActivity(intent1);
////        UpdateManager2 mUpdateManger = new UpdateManager2(HomeActivity.this);// 注意此处不能传入getApplicationContext();会报错，因为只有是一个Activity才可以添加窗体
////        mUpdateManger.checkUpdateInfo();
//        UpdateManager manager=new UpdateManager(HomeActivity.this);
//        manager.checkUpdateInfo();

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        hideBottomUIMenu();
        //preventStatusBarExpansion(this);
        SameTime();
        SetScreenLight();
        if(TimeUtil.DayNight()==1)
            physicalLight("亮灯");
        else
            physicalLight("灭灯");
        setContentView(R.layout.activity_home2);
        mSwipeRefreshLayout = (ViewPagerSwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        calling = (Button) findViewById(R.id.call);
        hidden_setting = (Button) findViewById(R.id.hidden_setting);
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        help = (Button) findViewById(R.id.help);
        change_medi = (Button) findViewById(R.id.change_medi);
        wifi = (ImageView)findViewById(R.id.wifi);
        //默认 >3 的选中效果会影响ViewPager的滑动切换时的效果，故利用反射去掉
        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);

        bottomNavigationView.setOnNavigationItemSelectedListener(  //menuItem的监听器，只有点击的时候会触发，滑动viewPager的时候不会触发
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        Log.d("Navigation", "change");
                        switch (item.getItemId()) {
                            case R.id.item_home:
                                viewPager.setCurrentItem(0); //设置viewPager的页面，viewPager.setCurrentItem会调用onPageSelected
                                break;
//                            case R.id.item_news:
//                                viewPager.setCurrentItem(1);
//                                break;
//                            case R.id.item_medi:
//                                viewPager.setCurrentItem(2);
//                                break;
//                            case R.id.item_fee:
//                                viewPager.setCurrentItem(3);
//                                break;
//                            case R.id.item_hospital:
//                                viewPager.setCurrentItem(4);
//                                break;
//                            case R.id.item_weather:
//                                viewPager.setCurrentItem(1);
//                                break;
                            case R.id.item_hospital:
                                viewPager.setCurrentItem(1);
                                break;
                        }
                        return false;
                    }
                });
        final Handler handler = new Handler(Looper.getMainLooper());
        mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

        calling.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if(HomeActivity.name == ""){
//                    Toast toast = Toast.makeText(HomeActivity.this,"连接服务器失败", Toast.LENGTH_SHORT);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    LinearLayout linearLayout = (LinearLayout) toast.getView();
//                    TextView messageTextView = (TextView) linearLayout.getChildAt(0);
//                    messageTextView.setTextColor(Color.parseColor("#FF0000"));
//                    messageTextView.setTextSize(60);//设置toast字体大小
//                    toast.show();
//                    return;
//                }
                new Thread(new Runnable() {

                    String body = null;

                    @Override
                    public void run() {
                        try {
                            String url_server = "http://" + server_ip + ":" + call_port + "";//添加路径
                            String url = url_server + path5 + "?deviceId=" + stationDeviceID;
                            System.out.println(url);
                            body = HttpUtils.get(url).body().string();
                            System.out.println("返回的body:" + body);
                        } catch (Exception e) {
                            //e.printStackTrace();
                            System.out.println("no response");
                        }
                        if (body != null && JSON.parseObject(body).containsKey("data")) {
                            Boolean isOnline = JSON.parseObject(body).getBoolean("data");
                            if (isOnline == true) {
                                new Thread(new Runnable() {

                                    String body = null;

                                    @Override
                                    public void run() {
                                        try {
                                            String url_server = "http://" + server_ip + ":" + info_port + "";//添加路径
                                            String url = url_server + path + "?ask=true" + "&id=" + bedID + "&type=call";
                                            System.out.println(url);
                                            body = HttpUtils.get(url).body().string();
                                            System.out.println("返回的body:" + body);
                                        } catch (Exception e) {
                                            //e.printStackTrace();
                                            System.out.println("no response");
                                        }
                                    }
                                }).start();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        t1 = "" + new Date().getTime() / 1000 * 1000;
                                        System.out.println("t1:" + t1);
                                        Handler handler1 = new Handler() {
                                            @Override
                                            public void handleMessage(Message msg) {
                                                calling.setEnabled(true);
                                            }
                                        };
                                        calling.setEnabled(false);
                                        handler1.postDelayed(null, 30000);
                                        if (!my_SignalClient.getInstance().websocketIsalive()) {
                                            if (!("".equals(socketUrl)) && !("".equals(localdeviceID))) {
                                                my_SignalClient.getInstance().startWebsocket(socketUrl, localdeviceID, HomeActivity.this);
                                            } else {
                                                Log.e(TAG, "请先从服务器请求websocket连接参数");
                                            }
                                        }
                                        my_SignalClient.getInstance().toUserId = stationDeviceID;
                                        my_SignalClient.getInstance().initiator = true; //标志我方为主动拨打的

                                        if (!"".equals(localdeviceID)) {

                                            if (CameraUtils.hasCamera(HomeActivity.this) && CameraUtils.isCameraCanUse()) {
                                                my_SignalClient.getInstance().isVideoCall = true;
                                                Intent intent = new Intent(HomeActivity.this, VideoCallActivity.class);
                                                startActivity(intent);
                                            } else {
                                                my_SignalClient.getInstance().isVideoCall = false;
                                                Intent intent = new Intent(HomeActivity.this, AudioCallActivity.class);
                                                startActivity(intent);
                                            }


                                        }
                                    }
                                });


                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast toast = Toast.makeText(HomeActivity.this, "护士站暂时不在线", Toast.LENGTH_SHORT);
                                        toast.setGravity(Gravity.CENTER, 0, 0);
                                        LinearLayout linearLayout = (LinearLayout) toast.getView();
                                        TextView messageTextView = (TextView) linearLayout.getChildAt(0);
                                        messageTextView.setTextColor(Color.parseColor("#FF0000"));
                                        messageTextView.setTextSize(60);//设置toast字体大小
                                        toast.show();
                                        Handler handler1 = new Handler() {
                                            @Override
                                            public void handleMessage(Message msg) {
                                                calling.setEnabled(true);
                                            }
                                        };
                                        calling.setEnabled(false);
                                        handler1.postDelayed(null, 30000);
                                    }
                                });

                            }
                        }

                    }
                }).start();

            }
        });

        help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if(HomeActivity.name == ""){
//                    Toast toast = Toast.makeText(HomeActivity.this,"连接服务器失败", Toast.LENGTH_SHORT);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    LinearLayout linearLayout = (LinearLayout) toast.getView();
//                    TextView messageTextView = (TextView) linearLayout.getChildAt(0);
//                    messageTextView.setTextColor(Color.parseColor("#FF0000"));
//                    messageTextView.setTextSize(60);//设置toast字体大小
//                    toast.show();
//                    return;
//                }
                if (is_help == false) {
                    is_help = true;
                    help.setText("已请求（长按取消）");
                    Toast toast = Toast.makeText(HomeActivity.this, "已发起求救", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    LinearLayout linearLayout = (LinearLayout) toast.getView();
                    TextView messageTextView = (TextView) linearLayout.getChildAt(0);
                    messageTextView.setTextColor(Color.parseColor("#FF0000"));
                    messageTextView.setTextSize(60);//设置toast字体大小
                    toast.show();
                    //help.setEnabled(false);
                    Handler handler1 = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            is_help = false;
                            help.setText("求助");
                            //help.setEnabled(true);
                        }
                    };
                    handler1.postDelayed(null, 300000);
                    new Thread(new Runnable() {

                        String body = null;

                        @Override
                        public void run() {
                            try {
                                String url_server = "http://" + server_ip + ":" + info_port + "";//添加路径
                                String url = url_server + path + "?ask=true" + "&id=" + bedID + "&type=help";
                                System.out.println(url);
                                body = HttpUtils.get(url).body().string();
                                System.out.println("返回的body:" + body);
                            } catch (Exception e) {
                                //e.printStackTrace();
                                System.out.println("no response");
                            }
                        }
                    }).start();
                }
            }
        });
        help.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
//                if(HomeActivity.name == ""){
//                    Toast toast = Toast.makeText(HomeActivity.this,"连接服务器失败", Toast.LENGTH_SHORT);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    LinearLayout linearLayout = (LinearLayout) toast.getView();
//                    TextView messageTextView = (TextView) linearLayout.getChildAt(0);
//                    messageTextView.setTextColor(Color.parseColor("#FF0000"));
//                    messageTextView.setTextSize(60);//设置toast字体大小
//                    toast.show();
//                    return false;
//                }
                if (is_help == true) {
                    is_help = false;
                    help.setText("求助");
                    new Thread(new Runnable() {

                        String body = null;

                        @Override
                        public void run() {
                            try {
                                String url_server = "http://" + server_ip + ":" + info_port + "";//添加路径
                                String url = url_server + path + "?ask=false" + "&id=" + bedID + "&type=help";
                                System.out.println(url);
                                body = HttpUtils.get(url).body().string();
                                System.out.println("返回的body:" + body);
                            } catch (Exception e) {
                                //e.printStackTrace();
                                System.out.println("no response");
                            }
                        }
                    }).start();
                }
                return true;
            }
        });

        change_medi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if(HomeActivity.name == ""){
//                    Toast toast = Toast.makeText(HomeActivity.this,"连接服务器失败", Toast.LENGTH_SHORT);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    LinearLayout linearLayout = (LinearLayout) toast.getView();
//                    TextView messageTextView = (TextView) linearLayout.getChildAt(0);
//                    messageTextView.setTextColor(Color.parseColor("#FF0000"));
//                    messageTextView.setTextSize(60);//设置toast字体大小
//                    toast.show();
//                    return;
//                }
                if (is_change == false) {
                    is_change = true;
                    change_medi.setText("已请求（长按取消）");
                    Toast toast = Toast.makeText(HomeActivity.this, "已发起换药请求", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    LinearLayout linearLayout = (LinearLayout) toast.getView();
                    TextView messageTextView = (TextView) linearLayout.getChildAt(0);
                    messageTextView.setTextColor(Color.parseColor("#FF0000"));
                    messageTextView.setTextSize(60);//设置toast字体大小
                    toast.show();
                    Handler handler1 = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            is_change = false;
                            change_medi.setText("换药");
                            //help.setEnabled(true);
                        }
                    };
                    handler1.postDelayed(null, 300000);
                    new Thread(new Runnable() {

                        String body = null;

                        @Override
                        public void run() {
                            try {
                                String url_server = "http://" + server_ip + ":" + info_port + "";//添加路径
                                String url = url_server + path + "?ask=true" + "&id=" + bedID + "&type=change";
                                System.out.println(url);
                                body = HttpUtils.get(url).body().string();
                                System.out.println("返回的body:" + body);
                            } catch (Exception e) {
                                //e.printStackTrace();
                                System.out.println("no response");
                            }
                        }
                    }).start();
                }

            }
        });
        change_medi.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
//                if(HomeActivity.bedID == 0){
//                    Toast toast = Toast.makeText(HomeActivity.this,"连接服务器失败", Toast.LENGTH_SHORT);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    LinearLayout linearLayout = (LinearLayout) toast.getView();
//                    TextView messageTextView = (TextView) linearLayout.getChildAt(0);
//                    messageTextView.setTextColor(Color.parseColor("#FF0000"));
//                    messageTextView.setTextSize(60);//设置toast字体大小
//                    toast.show();
//                    return false;
//                }
                if (is_change = true) {
                    is_change = false;
                    change_medi.setText("换药");
                    new Thread(new Runnable() {
                        String body = null;

                        @Override
                        public void run() {
                            try {
                                String url_server = "http://" + server_ip + ":" + info_port + "";//添加路径
                                String url = url_server + path + "?ask=false" + "&id=" + bedID + "&type=change";
                                System.out.println(url);
                                body = HttpUtils.get(url).body().string();
                                System.out.println("返回的body:" + body);
                            } catch (Exception e) {
                                //e.printStackTrace();
                                System.out.println("no response");
                            }
                        }
                    }).start();
                }

                return true;
            }
        });


        hidden_setting.setBackgroundColor(Color.TRANSPARENT); //设置按钮为透明的
        hidden_setting.setAlpha(0);
        hidden_setting.setOnClickListener(new View.OnClickListener() {
            final static int COUNTS = 8;//点击次数
            final static long DURATION = 3 * 1000;//规定有效时间
            long[] mHits = new long[COUNTS];

            @Override
            public void onClick(View v) {
                /**
                 * 实现双击方法
                 * src 拷贝的源数组
                 * srcPos 从源数组的那个位置开始拷贝.
                 * dst 目标数组
                 * dstPos 从目标数组的那个位子开始写数据
                 * length 拷贝的元素的个数
                 */
                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
                    String tips = "您已在[" + DURATION + "]ms内连续点击【" + mHits.length + "】次了！！！";
                    Toast.makeText(HomeActivity.this, tips, Toast.LENGTH_SHORT).show();

                    //业务逻辑
                    AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("是否打开系统设置界面？");
                    builder.setCancelable(false);
                    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent intent = new Intent(HomeActivity.this, HiddenSettingLoginActivity.class);
                            //intent.putExtra("ServerAddr", addr);
                            //intent.putExtra("userid", userId);
                            HomeActivity.this.startActivity(intent);


                        }
                    });
                    builder.setNegativeButton("No", null);
                    builder.show();

                }
            }
        });
        init_app_setting();

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mViewPagerAdapter.flash();
                //mViewPagerAdapter.getCount();
                //viewPager.setCurrentItem(0);
                viewPager.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        viewPager.setCurrentItem(mCurrentIndex);
                        mViewPagerAdapter.getItem(mCurrentIndex).setUserVisibleHint(true);//手动调用设置当前fragment为可见状态

                    }
                }, 1);
                //viewPager.setCurrentItem(mCurrentIndex);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSwipeRefreshLayout.setRefreshing(false);//设置刷新状态，true表示正在刷新，false表示取消刷新。
                    }
                }, 1000);
            }
        });

        //翻页监听
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //position说明：
            //当前显示页为0，前一页为-1，后一页为1，滑动过程中数值不断变大或变小，所以为float类型
            //参考：https://blog.csdn.net/weixin_39251617/article/details/79399592
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override   //滑动viewPager页面跳转完后调用
            public void onPageSelected(int position) {//划到第几页，position就是几，position的范围在0-3
                if (menuItem != null) {
                    menuItem.setChecked(false);
                } else {
                    bottomNavigationView.getMenu().getItem(0).setChecked(false);
                }
                menuItem = bottomNavigationView.getMenu().getItem(position);
                menuItem.setChecked(true); //设置这个menuItem为选中状态
                mCurrentIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        setupViewPager(viewPager, mViewPagerAdapter);
        //adjustNavigationIcoSize(bottomNavigationView);


        String local_ip = NetWorkUtils.getIPAddress(HomeActivity.this);
        Log.e(TAG, "打印Android端本地ip：" + local_ip);


        //相机和录音权限申请
        String[] perms;
        if (CameraUtils.hasCamera(HomeActivity.this)) {
            perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}; //如果有相机就申请两个权限，如果没有就申请一个权限
        } else {
            perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
        }

        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "Need permissions for camera & microphone", 0, perms);
        }

        //bottomNavigationView.setItemIconSize(20);

        // mq消息消费


    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(isPhysicalButton==false){
            isPhysicalButton = true;
            Handler handler1 = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    isPhysicalButton = false;
                }
            };
            handler1.postDelayed(null, 5000);
            switch (keyCode) {
                case KeyEvent.KEYCODE_F9://开始呼叫
                case KeyEvent.KEYCODE_F12://开始呼叫
                    calling.performClick();
                    return true;
                case KeyEvent.KEYCODE_F11://开始换药
                case KeyEvent.KEYCODE_F10://开始换药
                    if (is_change == true) {
                        change_medi.performLongClick();
                    } else if (is_change == false) {
                        change_medi.performClick();
                    }
                    return true;
            }
        }
        return super.onKeyUp(keyCode,event);
    }


    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }

    public static void preventStatusBarExpansion(Context context) {
        WindowManager manager = ((WindowManager) context.getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE));

        Activity activity = (Activity) context;
        WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
        localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
        localLayoutParams.gravity = Gravity.TOP;
        localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |

                // this is to enable the notification to receive touch events
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |

                // Draws over status bar
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;

        localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        int resId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        int result = 0;
        if (resId > 0) {
            result = activity.getResources().getDimensionPixelSize(resId);
        }

        localLayoutParams.height = result;

        localLayoutParams.format = PixelFormat.TRANSPARENT;

        customViewGroup view = new customViewGroup(context);

        manager.addView(view, localLayoutParams);
    }
    public void SameTime(){
        new Thread(new Runnable(){
            @Override
            public void run() {
                String url_weather = "http://10.19.0.2:8080/corridor/weather?city=丹凤";
                URL url = null;//取得资源对象
                try {
                    url = new URL(url_weather);
                    URLConnection uc = url.openConnection();//生成连接对象
                    uc.connect(); //发出连接
                    long ld = uc.getDate(); //取得网站日期时间
                    System.out.println("网站时间:"+ld);
                    SystemClock.setCurrentTimeMillis(ld);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


//    private void GetStationId() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                String body = null;
//                try {
//                    String url_server = "http://" + server_ip + ":" + info_port + "";//添加路径
//                    String url = url_server + path3 + "?id=" + stationDeviceID;
//                    System.out.println("GetStationId:"+url);
//                    body = HttpUtils.get(url).body().string();
//                    //Thread.sleep(2000);//等待get请求返回结果
//                } catch (Exception e) {
//                    //e.printStackTrace();
//                    System.out.println("no response");
//                }
//                System.out.println(body);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        HomeActivity.t1 = "";
//                        HomeActivity.t2 = "";
//                        HomeActivity.t3 = "";
//                    }
//                });
//            }
//
//        }).start();
//    }

    @Override
    protected void onStart() { //从设置界面里推出时，会调用这个函数
        Log.e("HomeActivity","onStart");
        super.onStart();
        SameTime();
        WifiHostBiz biz = new WifiHostBiz(getApplicationContext());
        if(biz.isWifiApEnabled()){
            wifi.setImageResource(R.mipmap.wifi);
        }

        if(TimeUtil.DayNight()==1)
            physicalLight("亮灯");
        else
            physicalLight("灭灯");
        HomeActivity.t1 = "";
        HomeActivity.t2 = "";
        HomeActivity.t3 = "";
        //检查是否已经配置了设置文件，如果是，则使按钮为不可见
        Log.e(TAG, "onStart被调用");
        if (CheckSettingUtils.isInitSetting(HomeActivity.this)) {

            hidden_setting.setBackgroundColor(Color.TRANSPARENT); //设置按钮为透明的
            hidden_setting.setText("");
            hidden_setting.setAlpha(0);
            JSONObject settingJson = JSONObject.parseObject(load("setting"));
            server_ip = settingJson.getString("server_ip");
            info_port = settingJson.getString("info_port");
            call_port = settingJson.getString("call_port");
            uuid = settingJson.getString("uuid");
            bedID = settingJson.getString("bedId");
            queue_num = settingJson.getString("queue_number");
            localdeviceID = settingJson.getString("deviceId");
            stationDeviceID = settingJson.getString("stationDeviceId");

            my_SignalClient.getInstance().toUserId = stationDeviceID;
            Log.e(TAG, "床号是：" + bedID);
            //打开websocket
            socketUrl = "ws://" + settingJson.getString("server_ip") + ":"
                    + settingJson.getString("call_port") +
                    "/call/patient/" + bedID + "/";
            //socketUrl= "ws://10.181.255.203:4433/call/patient/"+bedID+"/";
            my_SignalClient.getInstance().closeSocket();
            my_SignalClient.getInstance().startWebsocket(socketUrl, localdeviceID, HomeActivity.this);
            //开启websocket心跳检测
            my_SignalClient.getInstance().getmHandler().postDelayed(
                    my_SignalClient.getInstance().getHeartBeatRunnable(),
                    my_SignalClient.getInstance().getHeartBeatRate());

        }
        GetInfo();
        GetId();

        //GetStationId();
        ChangeSounds();


        if (CheckSettingUtils.isInitSetting(HomeActivity.this)) {
            MqConsumer.QUEUE_NUM = queue_num;
            MqConsumer.QUEUE_NAME = "bed" + stationDeviceID + "-" + bedID;
            MqConsumer.CONNECTION_NAME = "Android Consumer bed-" + bedID;
            MqConsumer.STATION_ID = stationId + "";
            consume();
        }

    }

    // 增加或减少天数
    public static Date addDay(Date date, int num) {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, num);
        return startDT.getTime();
    }
    public static void physicalLight(String type){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String hexString = null;
                switch (type){
                    case "亮灯":
                        hexString = "0110000000020401323232";
                        break;
                    case "闪灯":
                        hexString = "011000000008100232323201FF01FF";
                        break;
                    case "灭灯":
                        hexString = "011000000001020000";
                        break;
                }
                if (hexString==null)
                    return;
                System.out.println("灯光切换："+type);
                SerialPort.setSuPath("/system/xbin/su");
                String crc = getCRC(ByteUtil.hexStringToBytes(hexString));
                try {
                    SerialPort serialPort = new SerialPort(new File("/dev/ttyS5"), 9600, 0);
                    OutputStream outputStream = serialPort.getOutputStream();
                    System.out.println("发送数据为："+hexString+crc);
                    byte[] dataStream = ByteUtil.hexStringToByteArray(hexString+crc);
                    System.out.println(new String(dataStream));
                    outputStream.write(dataStream);
                    outputStream.flush();
                    serialPort.close();
                } catch (Exception e) {
                    System.out.println("串口通信出现错误");
                }
            }
        }).start();

    }
    public static String getCRC(byte[] bytes) {
        // CRC寄存器全为1
        int CRC = 0x0000ffff;
        // 多项式校验值
        int POLYNOMIAL = 0x0000a001;
        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        // 结果转换为16进制
        String result = Integer.toHexString(CRC).toUpperCase();
        if (result.length() != 4) {
            StringBuffer sb = new StringBuffer("0000");
            result = sb.replace(4 - result.length(), 4, result).toString();
        }
        //高位在前地位在后
        return result.substring(2, 4) + result.substring(0, 2);
        // 交换高低位，低位在前高位在后
//        return result.substring(2, 4) + result.substring(0, 2);
    }

    public void SetScreenLight() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Calendar calendar = Calendar.getInstance();
                /*** 定制每日23:00执行方法 ***/
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);

                Date date = calendar.getTime(); //第一次执行定时任务的时间
                System.out.println(date);
                System.out.println("before 方法比较：" + date.before(new Date()));
                //如果第一次执行定时任务的时间 小于 当前的时间
                //此时要在 第一次执行定时任务的时间 加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。循环执行的周期则以当前时间为准
                if (date.before(new Date())) {
                    date = addDay(date, 1);
                    System.out.println(date);
                }
                Timer timer = new Timer();

                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        Log.e("TimeTask","屏幕变暗");
                        DevicePolicyManager mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
                        mDPM.lockNow();
                        physicalLight("灭灯");
                        System.out.println("屏幕暗");
                    }
                };
                //安排指定的任务在指定的时间开始进行重复的固定延迟执行。
                timer.schedule(task, date, 24 * 60 * 60 * 1000);

                Calendar calendar2 = Calendar.getInstance();
                /*** 定制每日8:00执行方法 ***/
                calendar2.set(Calendar.HOUR_OF_DAY, 8);
                calendar2.set(Calendar.MINUTE, 0);
                calendar2.set(Calendar.SECOND, 0);

                Date date2 = calendar2.getTime(); //第一次执行定时任务的时间
                System.out.println(date2);
                System.out.println("before 方法比较：" + date2.before(new Date()));
                //如果第一次执行定时任务的时间 小于 当前的时间
                //此时要在 第一次执行定时任务的时间 加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。循环执行的周期则以当前时间为准
                if (date2.before(new Date())) {
                    date2 = addDay(date2, 1);
                    System.out.println(date2);
                }

                Timer timer2 = new Timer();
                TimerTask task2 = new TimerTask() {
                    @Override
                    public void run() {
                        System.out.println("屏幕亮");
                        physicalLight("亮灯");
                        PowerManager mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
                        @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
                        mWakeLock.acquire();
                    }
                };
                //安排指定的任务在指定的时间开始进行重复的固定延迟执行。
                timer2.schedule(task2, date2, 24 * 60 * 60 * 1000);
            }
        }).start();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        my_SignalClient.getInstance().closeSocket();//销毁Activity的时候才能销毁websocket
        physicalLight("灭灯");
    }

    private void init_app_setting() {
        //每次打开应用程序都要首先判断内部存储中是否存在setting
        //如果有就使用那个setting，如果没有就直接用asset中的default_setting来写到内部存储中
        //之后不管哪里，只要用到setting就用内部存储中的那个setting就好了

        if (CheckSettingUtils.isInitSetting(HomeActivity.this)) {
            hidden_setting.setAlpha(0);
            hidden_setting.setBackgroundColor(Color.TRANSPARENT); //设置按钮为透明的
            hidden_setting.setText("");
        } else {
            //表明尚未手动配置设置文件
            try { //如果setting不存在则将asset下面的setting内容复制到内部存储中
                AssetManager assetManager = getAssets(); //获得assets资源管理器（assets中的文件无法直接访问，可以使用AssetManager访问）
                InputStreamReader inputStreamReader = new InputStreamReader(assetManager.open("default_setting.json"), "UTF-8"); //使用IO流读取json文件内容

                BufferedReader br = new BufferedReader(inputStreamReader);//使用字符高效流
                String line;
                StringBuilder builder = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    builder.append(line);
                }
                br.close();
                inputStreamReader.close();
                //不应该在这里post请求上传病床分机设备信息，因为这里的uuid还没生成，不能上传到服务器
                save("setting", builder.toString()); //保存数据到文件
                Log.e(TAG, "内部存储中不存在setting，将默认setting复制到内部存储中");

                hidden_setting.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
                hidden_setting.setText("请初始化配置设置文件");

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void setupViewPager(ViewPager viewPager, ViewPagerAdapter adapter) {
        adapter.addFragment(new HomeFragment()); //在这里创建了fragment对象
//        adapter.addFragment(new WeatherFragment());
//        adapter.addFragment(new NewsFragment());
//        adapter.addFragment(new DoctorAdviceFragment());
//        adapter.addFragment(new FeeQueryFragment());
        adapter.addFragment(new HospitalFragment());
        viewPager.setAdapter(adapter);
        //传入需要viewPager预加载的fragment的个数，即传入所有fragment的个数
        viewPager.setOffscreenPageLimit(adapter.getCount()); //为了避免fragment被杀死，启用预加载所有fragment，然后我们的懒加载才能起到他的作用

    }

    /**
     * mq消息消费
     */
    private void consume() {
        // mq连接
        setupConnectionFactory();
        // 在线程中获取消息，完成后续业务
        final Handler msgHandler = new Handler(message -> {
            String msg = message.getData().getString("msg");
            System.out.println("msg" + msg);
            //处理mq消息通知
            handleMessage(msg);
            return false;
        });

        // 开启消费者进程进行消息消费
        new Thread(() -> basicConsume(msgHandler)).start();
    }


    private void save(String file_name, String data) { //将文件保存到内部存储的files文件中，默认文件没有后缀，只有文件名
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = openFileOutput(file_name, Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String load(String file_name) {  //加载内部存储中的指定文件
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput(file_name);
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

    public static void ChangeSounds() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String body = null;
                try {
                    Thread.sleep(3000);
                    String url_server = "http://" + server_ip + ":" + info_port + "";//添加路径
                    String url = url_server + path2 + "?id=" + stationId;
                    System.out.println("ChangeSounds:"+url);
                    body = HttpUtils.get(url).body().string();
                    Thread.sleep(1000);//等待get请求返回结果
                } catch (Exception e) {
                    //e.printStackTrace();
                    System.out.println("no response");
                }
                System.out.println(body);
                if (body != null && JSON.parseObject(body).containsKey("data")) {
                    List<ShoutInfo> shoutInfos = new ArrayList<>();
                    JSONArray array = JSON.parseObject(body).getJSONArray("data");
                    int cd = JSON.parseObject(body).getInteger("code");
                    if (cd == 0) {

                        for (Object obj : array) {
                            shoutInfos.add(JSONObject.parseObject(obj.toString(), ShoutInfo.class));//get data
                        }
                        System.out.println("开始设置定时任务:"+shoutInfos.size());
                        SetTimeTask(shoutInfos);
                    }
                }
            }

        }).start();
    }

    public static void SetTimeTask(List<ShoutInfo> shoutInfos) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (timer != null){
                    timer.cancel();
                    timer = null;
                }

                timer = new Timer();
                System.out.println(shoutInfos);
                for (ShoutInfo sh : shoutInfos) {
                    Calendar calendar = Calendar.getInstance();
                    /*** 定制每日执行方法 ***/
                    String startTime = sh.startTime;
                    int hour = Integer.parseInt(startTime.substring(0, 2));
                    int minute = Integer.parseInt(startTime.substring(3, 5));

                    calendar.set(Calendar.HOUR_OF_DAY, hour);
                    calendar.set(Calendar.MINUTE, minute);
                    calendar.set(Calendar.SECOND, 0);

                    Date date = calendar.getTime(); //第一次执行定时任务的时间
                    System.out.println(date);
                    System.out.println("before 方法比较(定时广播)：" + date.before(new Date()));
                    //如果第一次执行定时任务的时间 小于 当前的时间
                    //此时要在 第一次执行定时任务的时间 加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。循环执行的周期则以当前时间为准
                    if (date.before(new Date())) {
                        date = addDay(date, 1);
                        System.out.println(date);
                    }
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            playVoice(sh.cycleNumber, sh.url);
                        }
                    };
                    timer.schedule(task, date, 24 * 60 * 60 * 1000);

                }


            }

        }).start();
    }

    public static void playVoice(final int cycleNumber, String url) {
        //TODO: 后台播放音频
        new Thread(new Runnable() {//使用子线程播放
            boolean isRelease = true;//设计暂停功能
            MediaPlayer mediaPlayer;
            int num = cycleNumber;

            @Override
            public void run() {

                if (url != null) {
                    try {
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(url);
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mediaPlayer.prepareAsync();
                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                if (isRelease) {
                                    Log.e("MediaPlayer ", "开始播放");
                                    mp.start();
                                    num--;
                                    //isRelease = false;
                                }
                            }
                        });
                        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                // 在播放完毕被回调
                                if (num > 0) {
                                    Log.e("MediaPlayer ", "开始播放");
                                    mp.start();
                                    num--;
                                    //isRelease = false;
                                }

                            }
                        });
//                        {//有来电
//                            mediaPlayer.pause();
//                        }
//                        {//结束
//                            mediaPlayer.reset();     //重置MediaPlayer
//                            mediaPlayer.release();
//                            isRelease = true;
//                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else
                    Log.e("MediaPlayer", "地址错误");
            }
        }).start();

    }

    public static void GetId() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String body = null;
                try {
                    String url_server = "http://" + server_ip + ":" + info_port + "";//添加路径
                    String url = url_server + path3 + "?stationDeviceId=" + stationDeviceID;
                    System.out.println("GetId:"+url);
                    body = HttpUtils.get(url).body().string();
                    Thread.sleep(1000);//等待get请求返回结果
                } catch (Exception e) {
                    //e.printStackTrace();
                    System.out.println("no response");
                }
                System.out.println(body);
                if (body != null && JSON.parseObject(body).containsKey("data") && JSON.parseObject(body).getString("data") != null) {
                    stationId = JSON.parseObject(body).getInteger("data");
                }
            }

        }).start();
    }

    private void GetInfo() {
        HttpUtils okObject = new HttpUtils();
        t1 = "";
        t2 = "";
        t3 = "";
        new Thread(new Runnable() {

            String body = null;

            @Override
            public void run() {
                try {
                    String url_server = "http://" + server_ip + ":" + info_port + "";//添加路径
                    String url = url_server + "/getHospitalLink";
                    System.out.println(url);
                    body = HttpUtils.get(url).body().string();
                    System.out.println("返回的body:" + body);
                } catch (Exception e) {
                    //e.printStackTrace();
                    System.out.println("no response");
                }
                if (body != null && JSON.parseObject(body).containsKey("data")) {
                    hospital_url = JSON.parseObject(body).getString("data");
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String body = null;
                try {
                    String url = "http://" + server_ip + ":" + info_port + "/bed/index?id=" + bedID;
                    System.out.println("url:" + url);
                    body = okObject.get(url).body().string();
                    Thread.sleep(2000);//等待get请求返回结果
                } catch (Exception e) {
                    //e.printStackTrace();
                    System.out.println("no response");
                }
                System.out.println("首页请求信息:" + body);
                if (body != null && !JSON.parseObject(body).containsKey("timestamp")) {
                    JSONObject data = JSON.parseObject(body).getJSONObject("data");
                    room = data.getString("room");
                    code = data.getString("code");
                    patientId = data.getInteger("patientId");
                    name = data.getString("name");
                    gender = data.getString("gender");
                    profile = data.getString("profile");
                    age = data.getInteger("age");
                    admissionDate = data.getString("admissionDate");
                    level = data.getInteger("level");
                    pno = data.getString("pno");
                    office = data.getString("office");
                    doctor = data.getString("doctor");
                    nurse = data.getString("nurse");
                    conditions = data.getJSONArray("condition");
                    advices = data.getJSONArray("advice");

                }
            }

        }).start();
    }
}